/*
 * Copyright (C) 2010 Ryan Morton
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.games.rm.patternpuzzler;

import android.os.Handler;
import android.widget.TextView;
/***
 * 
 * @description: A simple timer that starts at 3 sec. and counts down to 0.
 * The passed TextView is updated every sec. with the current time left.
 */
public class CountdownTimer implements Runnable
{
	public static int START_TIME = 3;//time in sec
	private TextView myTextView;
	private CountdownTimerFinishedListener myListener;
	private Handler myHandler;
	private int currentTime = CountdownTimer.START_TIME;
	
	/***
	 * 
	 * @param tv the TextView that the countdown timer much update/change
	 * @param h handler from the main ui thread... new Handler() works
	 */
	public CountdownTimer(TextView tv, Handler h) 
	{
		myTextView = tv;
		myTextView.setText(""+CountdownTimer.START_TIME);
		myHandler = h;
	}
	
	@Override
	public void run()
	{
		//System.out.println(currentTime);
		currentTime--;
		
		myTextView.setText(""+currentTime);
		
		if(currentTime <= 0)
		{
			if(myListener != null)
			{
				myListener.onCountdownFinished();
			}
		}
		//continue
		else
		{
			myHandler.removeCallbacks(this);
	        myHandler.postDelayed(this, 1000);
		}
	}
	
	public boolean restart()
	{
		currentTime = CountdownTimer.START_TIME;
		myTextView.setText(""+CountdownTimer.START_TIME);
		this.start();
		return true;
	}
	
	public boolean start()
	{
		myHandler.removeCallbacks(this);
        myHandler.postDelayed(this, 1000);
        return true;
	}
	
	public void setTimerListener(CountdownTimerFinishedListener listener)
	{
		myListener = listener;
	}
}
